package com.kun.config;

import com.kun.auth.authmanager.AuthorizationManager;
import com.kun.auth.extractor.JwtOpaqueTokenIntrospector;
import com.kun.auth.handler.BearerTokenServerAccessDeniedHandler;
import com.kun.auth.handler.BearerTokenServerAuthenticationEntryPoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

/**
 * @author kun.li
 */
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {



    @Bean
    public SecurityWebFilterChain defaultSecurityFilterChain(ServerHttpSecurity http,
                                                             AuthorizationManager authorizationManager,
                                                             JwtOpaqueTokenIntrospector jwtOpaqueTokenIntrospector) {

        http.authorizeExchange((authorize) -> authorize
                .anyExchange().access(authorizationManager)
        );
        http.requestCache(ServerHttpSecurity.RequestCacheSpec::disable);
        http.oauth2ResourceServer(resourceServer -> {
            // 认证
            resourceServer.opaqueToken(opaqueTokenConfigurer -> {
                opaqueTokenConfigurer.introspector(jwtOpaqueTokenIntrospector);
            });
            // 权限不足
            resourceServer.accessDeniedHandler(new BearerTokenServerAccessDeniedHandler());
            // token 被移除,失效,没有传入token等
            resourceServer.authenticationEntryPoint(new BearerTokenServerAuthenticationEntryPoint());
        });
        http.cors(ServerHttpSecurity.CorsSpec::disable);
        http.csrf(ServerHttpSecurity.CsrfSpec::disable);
        return http.build();
    }


    /**
     * issuer 根据这个路径拼接 /.well-known/oauth-authorization-server 获取所有认证接口
     * issuer地址应该和认证中心配置的地址一致
     * 用来验证用户传入的认证token中的issuer和本地配置的是否一致
     * 不一致说明token验证失败 否则成功
     *
     * @return
     */
//    @Bean
//    public ReactiveJwtDecoder reactiveJwtDecoder() {
//        return ReactiveJwtDecoders.fromIssuerLocation("http://192.168.56.1:9200");
//    }


}
